package com.dadie.dorm.controller;


import com.dadie.dorm.pojo.User;
import com.dadie.dorm.service.IUserService;
import com.dadie.dorm.service.impl.UserServiceImpl;
import com.dadie.dorm.util.JSONUtil;
import com.dadie.dorm.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");

        switch (method) {
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req, resp);
                break;
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.logout");
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet.login");
        String name=req.getParameter("name");
        String password=req.getParameter("password");
        String code=req.getParameter("code");

        HttpSession session=req.getSession();
        String codeInSession=(String) session.getAttribute("codeInSession");
        if(!codeInSession.equalsIgnoreCase(code)){
            Map<String,Object> map =new HashMap<>();
            map.put("code",1);
            map.put("msg","验证码错误");
            JSONUtil.toJSON(resp,map);
            return;
        }
User user=userService.login(name, password);
        if(user!=null){
            session.setAttribute("user",user);
            Map<String,Object> map=new HashMap<>();
            map.put("code",0);
            map.put("msg","登陆成功");
            JSONUtil.toJSON(resp, map);
        }else {
            Map<String,Object> map=new HashMap<>();
            map.put("code",1);
            map.put("msg","用户名或密码错误");
        }
    }

}
